package com.rssfeed.utility;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;

public class CommonUtils{
	private CharSequence mFormattedDate = "";
	
	public static boolean isNetworkAvailable(Activity mainActivity) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mainActivity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

    long mTimeFormatted = 0;

    public void setTimestamp(Context mContext, long timestamp) {
        if (mTimeFormatted != timestamp) {
            mFormattedDate = DateUtils.getRelativeTimeSpanString(mContext, timestamp).toString();
            mTimeFormatted = timestamp;
        }
    }
    

	
	public static String getCurrentTimeStamp(String format) {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
		Date now = new Date();
		String strDate = sdf.format(now);

		return strDate;
	}

	public static String getTime() {
		String date = null;
		Calendar c = Calendar.getInstance();
		int hours = c.get(Calendar.HOUR_OF_DAY);
		int minutes = c.get(Calendar.MINUTE);
		int seconds = c.get(Calendar.SECOND);

		return hours + "-" + minutes + "-" + seconds;
	}

	public static int convertPxToDp(Context context, int px) {
		Resources resources = context.getResources();
		DisplayMetrics displayMetrics = resources.getDisplayMetrics();
		displayMetrics = context.getResources().getDisplayMetrics();
		return (int) ((px / displayMetrics.density) + 0.5);
	}

	public static String getAllApp(Activity activity) {
		List<ApplicationInfo> packages;
		PackageManager pm;
		String post = "currentApp=" + activity.getPackageName()
				+ "&installedApps=";
		pm = activity.getPackageManager();
		packages = pm.getInstalledApplications(PackageManager.GET_META_DATA
				| PackageManager.GET_ACTIVITIES);
		int index = 0;
		for (int i = 0; i < packages.size(); i++) {
			ApplicationInfo packageInfo = packages.get(i);
			if ((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
				continue;
			}
			if (index == 0) {
				post += packageInfo.packageName;
				index = 1;
			} else
				post += "," + packageInfo.packageName;
		}
		return post;
	}


	/**
	 * A helper method to convert an InputStream into a String
	 * 
	 * @param inputStream
	 * @return the String or a blank string if the IS was null
	 * @throws IOException
	 */
	public static String convertToString(InputStream inputStream)
			throws IOException {
		if (inputStream != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(
						inputStream, "UTF-8"), 1024);
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				inputStream.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}

	/**
	 * Copy stream from inputStream into ouputStream
	 * 
	 * @param is
	 *            : InputStream
	 * @param os
	 *            : OuputStream
	 */
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	public static String convertTime(long millis) {
		String hms = "";
		Object[] arrayOfObject = new Object[3];
		
		arrayOfObject[2] = (int) (millis / 1000) % 60;
		arrayOfObject[1] = (int) ((millis / (1000 * 60)) % 60);
		arrayOfObject[0] = (int) ((millis / (1000 * 60 * 60)) % 24);

		hms = String.format("%01d:%02d:%02d", arrayOfObject);

		return hms;
	}

	
	public static String getDate(long milliSeconds, String dateFormat) {
		// Create a DateFormatter object for displaying date in specified
		// format.
		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat,
				Locale.getDefault());

		// Create a calendar object that will convert the date and time value in
		// milliseconds to date.
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliSeconds);
		return formatter.format(calendar.getTime());
	}

	public static String TimeDiff(long timeMilliseconds) {
		
		long now = System.currentTimeMillis();
		long timeDifferenceMilliseconds = now - timeMilliseconds;
		long diffSeconds = timeDifferenceMilliseconds / 1000;
		long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
		long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
		long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
//		long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
//		long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
//		long diffYears = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 365));

		if (diffSeconds < 1) {
			return "less than a second ago";
		} else if (diffMinutes < 1) {
			return diffSeconds + " seconds ago";
		} else if (diffHours < 1) {
			return diffMinutes + " minutes ago";
		} else if (diffDays < 1) {
			return diffHours + " hours ago";
		} else {
			//return diffDays + " days ago";
			return CommonUtils.getDate(timeMilliseconds, "dd/MM/yyyy HH:mm:ss");
		} 
	}
	
	public static String friendlyTimeDiff(long timeDifferenceMilliseconds) {
		long diffSeconds = timeDifferenceMilliseconds / 1000;
		long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
		long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
		long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
		long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
		long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
		long diffYears = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 365));

		if (diffSeconds < 1) {
			return "less than a second ago";
		} else if (diffMinutes < 1) {
			return diffSeconds + " seconds ago";
		} else if (diffHours < 1) {
			return diffMinutes + " minutes ago";
		} else if (diffDays < 1) {
			return diffHours + " hours ago";
		} else if (diffWeeks < 1) {
			return diffDays + " days ago";
		} else if (diffMonths < 1) {
			return diffWeeks + " weeks ago";
		} else if (diffYears < 1) {
			return diffMonths + " months ago";
		} else {
			return diffYears + " years ago";
		}
	}

	public static boolean isNumeric(String str) {
		try {
			double d = Double.parseDouble(str);
		} catch (NumberFormatException nfe) {
			return false;
		}
		return true;
	}
	
	public static DisplayMetrics a(Activity paramActivity)
	  {
	    if (paramActivity.getWindowManager() == null)
	      return null;
	    DisplayMetrics localDisplayMetrics = new DisplayMetrics();
	    paramActivity.getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
	    return localDisplayMetrics;
	  }

	public static void linkGooglePlay(Context context) {
		Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
		Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
		try {
		  context.startActivity(goToMarket);
		} catch (ActivityNotFoundException e) {
			context.startActivity(new Intent(Intent.ACTION_VIEW, 
					Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
		}
	}
	
	public static void linkGooglePlay(Context context, String packageName) {
		Uri uri = Uri.parse("market://details?id=" + packageName);
		Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
		try {
		  context.startActivity(goToMarket);
		} catch (ActivityNotFoundException e) {
			context.startActivity(new Intent(Intent.ACTION_VIEW, 
					Uri.parse("http://play.google.com/store/apps/details?id=" + packageName)));
		}
	}
	
	public static String formatFileSize(long size) {
	    String hrSize = null;

	    double b = size;
	    double k = size/1024.0;
	    double m = ((size/1024.0)/1024.0);
	    double g = (((size/1024.0)/1024.0)/1024.0);
	    double t = ((((size/1024.0)/1024.0)/1024.0)/1024.0);

	    DecimalFormat dec = new DecimalFormat("0.00");

	    if ( t>1 ) {
	        hrSize = dec.format(t).concat(" TB");
	    } else if ( g>1 ) {
	        hrSize = dec.format(g).concat(" GB");
	    } else if ( m>1 ) {
	        hrSize = dec.format(m).concat(" MB");
	    } else if ( k>1 ) {
	        hrSize = dec.format(k).concat(" KB");
	    } else {
	        hrSize = dec.format(b).concat(" Bytes");
	    }

	    return hrSize;
	}

}
